package com.example.project.projectspringcloud.controller.front.user;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.controller.BaseController;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.order.Order;
import com.example.project.projectspringcloud.entity.user.Evaluate;
import com.example.project.projectspringcloud.entity.user.User;
import com.example.project.projectspringcloud.entity.user.pojo.EvaluatePojo;
import com.example.project.projectspringcloud.service.order.OrderService;
import com.example.project.projectspringcloud.service.user.UserEvaluateService;
import com.example.project.projectspringcloud.utils.WebUtil;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Api(value = "用户端评价Controller")
@RequestMapping(value = "/evaluate")
@Controller
public class EvaluateController extends BaseController {

    @Autowired
    private UserEvaluateService userEvaluateService;

    @Autowired
    private OrderService orderService;

    @ApiOperation(value = "用户评价列表", notes = "返回用户评价列表")
    @GetMapping(value = "/list/{status}")
    public String list(@PathVariable("status") Integer status,
                       @RequestParam(value = "range", required = false) Integer range,
                       @RequestParam(value = "method", required = false) Integer method, Page page, Model model) {
        Order order = new Order();
        order.setUserId(getCurrentUser().getId());
        order.setStatus(Constants.OrderStatus.PAID);
        // 查询按同款和私人订制 1. 同款 2. 私人订制
        order.setSelectByProductionMethod(method);
        switch (status) {
            // 待评价
            case 1:
                order.setSelectByEvaluateStatus(1);
                break;
            // 已评价
            case 2:
                order.setSelectByEvaluateStatus(2);
                break;
        }
        if (range != null) {
            switch (range) {
                case 1:
                    // 七天之内
                    order.setRange(7);
                    break;
                case 2:
                    // 三个月
                    order.setRange(90);
                    break;
                case 3:
                    // 半年
                    order.setRange(183);
                    break;
            }
        }
        List<Order> orders = orderService.list(page, order);
        model.addAttribute("page", new Page<Order>(orders));
        model.addAttribute("status", status);
        model.addAttribute("method", method);
        model.addAttribute("range", range);
        return isMobile() ? "m/content/order/evaluate-list" : "content/order/evaluate-list";
    }


    @ApiOperation(value = "编写评价页面", notes = "返回编写评价页面")
    @GetMapping(value = "/ready")
    public String ready(@RequestParam("targetType") Integer targetType, @RequestParam("target") Integer target,
                        Model model) {
        model.addAttribute("targetType", targetType);
        model.addAttribute("target", target);

        // TODO 返回摄影师/编剧头像
        switch (targetType) {
            case 3:
                Order order = new Order();
                order.setStatus(Constants.OrderStatus.PAID);
                order.setUserId(getCurrentUser().getId());
                order.setId(target);
                order = orderService.get(order);
                model.addAttribute("order", order);
                break;
        }
        return isMobile() ? "m/content/order/evaluate-form" : "content/order/evaluate-form";
    }

    @ApiOperation(value = "提交评价", notes = "提交评价")
    @PostMapping(value = "/add")
    public String add(EvaluatePojo pojo, Model model) throws Exception {
        Order order = orderService.get(new Order(pojo.getTarget()));
        if (order == null) {
            model.addAttribute("error", super.translateI18N(Constants.Message.ORDER_DOES_NOT_EXIST));
            return "redirect:/evaluate/ready?target=" + pojo.getTarget();
        }
        boolean result = userEvaluateService.evaluate(pojo);
        if (!result) {
            model.addAttribute("error", super.translateI18N(Constants.Tip.ORDER_EVALUATE_ALREADY_EXIST));
        }
        return "redirect:/evaluate/detail/" + order.getId();
    }

    @ApiOperation(value = "评价详情", notes = "返回评价详情页面")
    @GetMapping(value = "/detail/{orderId}")
    public String detail(@PathVariable("orderId") Integer orderId, Model model) {
        Order order = new Order();
        order.setUserId(super.getCurrentUser().getId());
        order.setId(orderId);
        order = orderService.get(order);
        if (Optional.ofNullable(order).isPresent()) {
            Evaluate evaluate = new Evaluate();
            evaluate.setUserId(getCurrentUser().getId());
            evaluate.setTarget(orderId);
            List<Evaluate> evaluates = userEvaluateService.list(null, evaluate);

            // 获取对应订单的对摄影师的评价
            evaluate.setTarget(order.getOrderDetail().getPhotographer());
            evaluate.setCreateDate(evaluates.get(0).getCreateDate());
            evaluates.add(userEvaluateService.get(evaluate));

            // 获取对应订单的对编剧的评价
            evaluate.setTarget(order.getOrderDetail().getScriptwriter());
            evaluate.setCreateDate(evaluates.get(0).getCreateDate());
            evaluates.add(userEvaluateService.get(evaluate));

            // 如果是同款, 再获取对同款作品的评价, 作为本订单作品评价
            if (order.getType().equals(1)) {
                evaluate.setTarget(order.getOrderDetail().getSameStyleId());
                evaluate.setCreateDate(evaluates.get(0).getCreateDate());
                evaluates.add(userEvaluateService.get(evaluate));
            }
            evaluates = evaluates.stream().sorted(Comparator.comparing(Evaluate::getTargetType)).collect(Collectors.toList());
            model.addAttribute("evaluates", evaluates);
        }
        model.addAttribute("order", order);
        return isMobile() ? "m/content/order/evaluate-detail" : "content/order/evaluate-detail";
    }

    @ApiOperation(value = "API添加评价", notes = "用户创建评价")
    @PostMapping(value = "/api/add")
    @ResponseBody
    public RespBody add(Evaluate evaluate) throws Exception {
        User currentUser = WebUtil.getCurrentUser();
        evaluate.setUserId(currentUser.getId());
        userEvaluateService.save(evaluate);
        return RespBody.ok(true);
    }

    @ApiOperation(value = "API用户评价列表", notes = "返回用户评价列表数据")
    @GetMapping(value = "/api/list/{status}")
    @ResponseBody
    public RespBody list(@PathVariable("status") Integer status,
                         @RequestParam(value = "range", required = false) Integer range,
                         @RequestParam(value = "method", required = false) Integer method,
                         @RequestParam(value = "searchWord", required = false) String searchWord,
                         Page page) {
        Order order = new Order();
        order.setUserId(getCurrentUser().getId());
        order.setStatus(Constants.OrderStatus.PAID);
        order.setSearchWord(searchWord);
        // 查询按同款和私人订制 1. 同款 2. 私人订制
        order.setSelectByProductionMethod(method);
        switch (status) {
            // 待评价
            case 1:
                order.setSelectByEvaluateStatus(1);
                break;
            // 已评价
            case 2:
                order.setSelectByEvaluateStatus(2);
                break;
        }
        if (range != null) {
            switch (range) {
                case 1:
                    // 七天之内
                    order.setRange(7);
                    break;
                case 2:
                    // 三个月
                    order.setRange(90);
                    break;
                case 3:
                    // 半年
                    order.setRange(183);
                    break;
            }
        }
        List<Order> orders = orderService.list(page, order);
        Map result = Maps.newHashMap();
        result.put("page", new Page<Order>(orders));
        result.put("status", status);
        result.put("method", method);
        result.put("range", range);
        return RespBody.ok(result);
    }

    @ApiOperation(value = "API返回评论数据", notes = "仅返回评论数据")
    @GetMapping(value = "/api/data")
    @ResponseBody
    public RespBody data(Evaluate evaluate, Page page) throws Exception {
        // 获取评价
        List<Evaluate> evaluates = userEvaluateService.list(null, evaluate);
        return RespBody.ok(new Page<Evaluate>(evaluates));
    }
}
